<template>
  <div class="app-container">
    <div>
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <el-button v-show="true" @click="print">打印</el-button>
          <el-button v-show="true" @click="exportExcel">导出excel</el-button>
        </NewPageFilter>
        <div class="display-flex">
          <GroupSelect
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
          ></GroupSelect>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        v-if="groupFlag"
        class="groupFlag-container"
        :is-group-search="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="false"
        :pager="false"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
        :allSummary="true"
        :allSummaryData="allSummaryData"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      />
      <TableContainer
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="true"
        :tab-index="true"
        :summary="true"
        :summary-field-list="tableInfo.summaryFieldList"
        v-model:query="filterInfo.query"
        :handle="tableInfo.handle"
        :field-list="tableInfo.fieldList"
        :all-summary="true"
        :all-summary-data="allSummaryData"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
      </TableContainer>
    </div>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <IndividualDetails
      v-if="showIndividualDetails"
      v-model:showDialog="showIndividualDetails"
      v-model:query="paramsIndividual"
      :info="productInfo"
    ></IndividualDetails>
  </div>
</template>

<script setup name="cargoSpaceStockQuery">
import {
  getCargoSpaceStockQueryCustomizeList,
  getCargoSpaceStockQueryCustomizeAll,
  getCargoSpaceStockQueryCustomizeGroups,
  cargoSpaceStockQueryExcel,
  cargoSpaceStockQueryPrint,
  getCargoStockQueryCustomizeSumAmount,
} from '@/api/dataQuery.js'
import IndividualDetails from './IndividualDetails'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'

import { getDepotAllUseTypeIdOr } from '@/api/core'
const { proxy } = getCurrentInstance()
const route = useRoute()
const time = ref([])
const showIndividualDetails = ref(false)
const paramsIndividual = ref({})
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)
// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    groupMap: {},
    groups: [],
    queryMap: {
      depotAuth: {
        queryType: 'IN',
        asTbName: 'wms_shelf_stock',
        columnName: 'depot_id',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
    queryParams: {
      calcQtyGtZero: 1,
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '打印',
      event: print,
      show: proxy.$permission('cargoSpaceStockQuery:print'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('cargoSpaceStockQuery:excel'),
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.TripartiteMethod },
    { value: 'frozenQty', formatter: proxy.$fn.TripartiteMethod },
    { value: 'stockAvailableQty', formatter: proxy.$fn.TripartiteMethod },
    { value: 'pendStoreQty', formatter: proxy.$fn.TripartiteMethod },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: individualDetails,
        show: true,
      },
    ],
  },
})
const allSummaryData = ref({
  data: [],
  fieldList: [
    {
      label: '总金额',
      value: 'sumStockAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const productInfo = ref({})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
watch(
  () => route,
  async (route) => {
    const params = route.params
    if (route.name === 'cargoSpaceStockQuery') {
      if (await Object.keys(params).length) {
        filterInfo.value.query.queryMap = proxy.$fn.deepClone(
          filterInfo.value.copyQueryMap
        )
        clearType.value = !clearType.value
        preferenceInfo.value.visible = false
        showIndividualDetails.value = false
        advancedSearchInfo.value.visible = false
        filterInfo.value.query.groups = []
        filterInfo.value.query.groupMap = {}
        groupSelectInfo.value.data = []
        groupFlag.value = false
        advancedSearchInfo.value.data = {}
        let timer = setTimeout(() => {
          let query = {
            depotId: {
              queryType: 'IN',
              value: params.depotId.toString(),
            },
          }
          filterInfo.value.query.queryMap = {
            ...filterInfo.value.query.queryMap,
            ...query,
          }
          getList()
          clearTimeout(timer)
        }, 500)
      }
    }
  },
  { immediate: true }
)
function pageInfo(obj) {
  page.value = obj
}
// 关闭弹窗前的回调
function handleClose() {
  dialogInfo.value.visible = false
  proxy.$emit('reset')
}
function returnModify() {
  getList()
}
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.value.query.groups = arr
    groupSelectInfo.value.selections = arr
    getCustomizeGroupsList()
  } else {
    proxy.$message.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.value.query
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getCargoSpaceStockQueryCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.value.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCargoSpaceStockQueryCustomizeAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
function setPreferenceCallback(obj) {
  slipSelectRequest.value = !slipSelectRequest.value
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'wms_shelf_stock',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  if (groupSelectInfo.value.selections.length > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    await getList()
  }
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
  getSummary()
}
// 搜索
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  if (groupSelectInfo.value.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
    getSummary()
  }
}
//个体详情
function individualDetails(row) {
  paramsIndividual.value['id'] = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: row.groupConcatIds,
  }
  productInfo.value = row
  showIndividualDetails.value = true
  console.log(
    '🚀 ~ file: index.vue ~ line 462 ~ individualDetails ~ showIndividualDetails',
    showIndividualDetails.value
  )
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  cargoSpaceStockQueryExcel(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'cargoSpaceStockQuery:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  cargoSpaceStockQueryPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}

function getCustomize() {
  let param = {
    tableKey:
      'wmsShelfStockQueryList-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      tableInfo.value.api = getCargoSpaceStockQueryCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.value.fieldList.length,
      }
    }
  }
}
function getSummary() {
  let params = {}
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(filterInfo.value.query)
    params.queryMap = {}
  } else {
    params = filterInfo.value.query
  }
  getCargoStockQueryCustomizeSumAmount(params).then((res) => {
    if (res && res.success) {
      if (res.data && res.data[0] !== null) {
        allSummaryData.value.data = [{ sumStockAmount: res.data }]
      } else {
        allSummaryData.value.data = []
      }
    }
  })
}

let obj = {
  depotName: {
    label: '出库仓库',
    value: 'depotName',
    asValue: 'depotId',
    componentType: 'slip-select',
    query: {
      depotAuth: 'id',
      status: 1,
      useTypeId: '1,2,3',
      isCargoSpaceManage: '1',
    },
    api: getDepotAllUseTypeIdOr,
    show: false,
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('cargoSpaceStockQuery:price'),
    hidden: true,
    show: false,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('cargoSpaceStockQuery:price'),
    hidden: true,
    show: false,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('cargoSpaceStockQuery:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  cargoSpaceNo: {
    label: '货位编码',
    value: 'cargoSpaceNo',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
getCustomize()
</script>

<style scoped></style>
